import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, Switch, message, Upload, Icon, Dropdown, Menu, Divider, Drawer, Button, Form, Input, Badge, Modal, Table, Descriptions } from 'antd';
import { BaseForm, PromotionChannelsForm } from '@/components/FormTools';
import { getAllCity, deleteData, getCityPaymentList, saveMaintenanceInfor } from '@/services/auth';
import { secMap } from '@/configs/api.map';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { getValue, to } from '@/utils/smallTool';
import { connect } from 'dva';
import moment from 'moment';
import styles from './index.less';
import authUtil from '@/utils/auth';
const today = moment(new Date(), 'YYYY/MM/DD').format('YYYY/MM/DD');
const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 20 };
const drawerConfig = {
  edit: {
    title: '编辑',
  },
  add: {
    title: '新增',
  },
};
const businessType = [{ value: '0', name: '社保' }, { value: '1', name: '公积金' }, { value: '2', name: '医疗支出' }, { value: '3', name: '公积金贷款' }];
const drawerWidth = 500;
const formProp = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
function getBusinessTypeByValue(value) {
  for (let i = 0; i < businessType.length; i++) {
    if (businessType[i].value == value) {
      return businessType[i].name;
    }
  }
}
@connect(({ global, loading, cityconfigmsg, authority }) => ({
  tableData: cityconfigmsg.tableData,
  IssueChannelList: cityconfigmsg.IssueChannelList,
  SalespersonList: cityconfigmsg.SalespersonList,
  ManufactureList: cityconfigmsg.ManufactureList,
  searchForm: cityconfigmsg.searchForm,
  permissionsList: authority.permissionsList,
  tableLoading: loading.effects['cityconfigmsg/getCityMsgByPage'],
  watermarkConfig: global.watermarkConfig,
}))
class CityConfigMsg extends PureComponent {
  state = {
    selectedRows: [],
    shieHideBatchDel: false,
    params: {},
    pageRequest: {
      pageNum: 1,
      pageSize: 10,
    },
    drawerStatus: {
      visible: false,
      type: 'add',
    },
    resultDate: [],
    loading: true,
    activeRecord: {},
    inputConfig: [
      {
        type: 'select',
        placeholder: '请选择城市名称',
        name: 'cityCode',
        label: '城市名称',
        optionData: [],
        nameFiled: 'cityName',
        valueFiled: 'cityCode',
        selectProps: {
          allowClear: true,
          optionFilterProp: 'children',
          showSearch: true
        }
      },
      {
        type: 'select',
        placeholder: '请选择业务类型',
        name: 'type',
        label: '业务类型',
        optionData: businessType,
        selectProps: {
          allowClear: true,
        }
      }
    ]
  };
  constructor(props) {
    super(props);
    this.$drawerForm = React.createRef();
    const { pageRequest, params } = this.state;
    this.getSelectList().then(res => {
      this.getQueryList(params, pageRequest);
    })
  }

  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    if (formData.insuranceTime && formData.insuranceTime.length !== 0) {
      params.jobDateStart = params.insuranceTime[0];
      params.jobDateEnd = params.insuranceTime[1];
      delete params.insuranceTime;
    }
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'cityconfigmsg/getCityMsgByPage';
    const param = Object.assign(pageRequest, params);
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: param,
    });
  };
  /**
   * @description 请求事件类型下拉列表数据
   * @author zhe
   * @date 2020-04-14
   * @memberof
   */
  getSelectList = async () => {
    const { inputConfig } = this.state;
    const dataObj = await getAllCity();
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data !== null) {
        inputConfig[0].optionData = dataObj.data;
        this.setState({ inputConfig: inputConfig });
        return Promise.resolve(dataObj.data);
      }
    }
    return Promise.reject();
  };
  /**
   * @description 删除
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  deleteData = async activeRecord => {
    const params = {};
    const { noticeId } = activeRecord;
    params.noticeId = noticeId;
    const dataObj = await deleteData(params);
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data !== null) {
        message.success('操作成功');
      } else {
        message.error('操作失败');
      }
    }
  };
  // comment=========================================================>>>>>>>>>>>>>>>>>>>>>>>>

  /**
   * @description table操作触发改变事件
   * @author songs
   * @date 2019-07-12
   * @param {*} pagination
   * @param {*} filtersArg
   * @param {*} sorter
   * @memberof managementUser
   */
  handleStandardTableChange = (pagination, filtersArg, sorter, actionType) => {
    const { pageSize, current } = pagination;
    const pageNum = current;
    const pageRequest = { pageSize, pageNum };
    this.getQueryList(filtersArg, pageRequest);
  };

  /**
   * @description 抽屉表单提交事件
   */
  onDrawerOk = async () => {
    const { drawerStatus } = this.state;
    const { getFieldsValue, validateFields } = this.$drawerForm.current.props.form;
    const drawerItem = drawerConfig[drawerStatus.type];
    let validateError = null;
    let validateRes = null;
    [validateError, validateRes] = await to(validateFields());
    if (validateError) return false;
    let postRes = false;
    validateRes.maintenanceTime = validateRes.time[0].format('YYYY/MM/DD');
    validateRes.repairTime = validateRes.time[1].format('YYYY/MM/DD');
    delete validateRes.time;
    const dataObj = await saveMaintenanceInfor(validateRes);
    if (dataObj && dataObj.code === '000000') {
      message.success('操作成功');
      const pageRequest = { pageNum: 1, pageSize: 10 };
      this.setState({
        params: {},
      });
      this.getQueryList(this.state.params, pageRequest);
      postRes = true;
    } else {
      postRes = false;
      message.error('操作失败');
    }
    if (postRes) this.changeDrawerStatus(false);
    return true;
  };

  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} type
   * @param {*} title
   */
  changeDrawerStatus = (visible, type = '', activeRecord = {}, event) => {
    this.setState(oldState => ({
      ...oldState,
      drawerStatus: { type, visible },
      activeRecord,
    }));
  };

  /**
   * @description 解析抽屉内表单配置信息
   * @param {*} type
   * @returns
   */
  ravDrawerConfig = type => {
    const { activeRecord, inputConfig } = this.state;
    const dateFormat = 'YYYY/MM/DD';
    return [
      {
        type: 'input',
        name: 'id',
        decorator: true,
        initialValue: activeRecord.id || '',
        isHide: true
      },
      {
        type: 'select',
        name: 'cityCode',
        label: '维护城市',
        decorator: true,
        initialValue: String(activeRecord.cityCode || ''),
        optionList: {
          name: 'cityName',
          value: 'cityCode',
          list: inputConfig[0].optionData
        },
        selectProps: {
          allowClear: true,
          optionFilterProp: 'children',
          showSearch: true
        },
        decoratorConfig: {
          rules: [{ required: true, message: '维护城市不能为空' }],
        },
      },
      {
        type: 'select',
        placeholder: '业务类型',
        name: 'type',
        decorator: true,
        initialValue: activeRecord.type > -1 ? String(activeRecord.type) : '',
        optionList: {
          list: businessType
        },
        label: '业务类型',
      },
      {
        type: 'input',
        name: 'reason',
        label: '维护原因',
        initialValue: activeRecord.reason || '',
        decorator: true,
        decoratorConfig: {
          rules: [{ required: true, message: '描述不能为空' }]
        }
      },
      {
        type: 'rangePicker',
        name: 'time',
        label: '维护时间',
        format: 'YYYY-MM-DD',
        decorator: true,
        grid: { sm: 24, md: 12, xl: 8, xxl: 8 },
        initialValue: [moment(activeRecord.maintenanceTime || today, dateFormat), moment(activeRecord.repairTime || today, dateFormat)],
        decoratorConfig: {
          rules: [{ required: true, message: '维护时间不能为空' }],
        },
      }
    ]
  };

  onHandleDelete = record => {
    const _this = this;
    this.deleteData(record).then(function () {
      const { params } = _this.state;
      const { tableData } = _this.props;
      const { pagination = {} } = tableData;
      const { pageNum, pageSize } = pagination;
      const pageRequest = { pageNum: pageNum, pageSize: pageSize };
      _this.getQueryList(params, pageRequest);
    });
  };

  tableCol = () => {
    const OptionNode = ({ record }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.changeDrawerStatus(true, 'edit', record);
          }}
        >
          编辑
        </Button>
      </div>
    );
    return [
      {
        title: '城市编号',
        dataIndex: 'cityCode',
        width: '10%'
      },
      {
        title: '城市名称',
        dataIndex: 'cityName',
        width: '10%'
      },
      {
        title: '业务类型',
        dataIndex: 'type',
        width: '10%',
        render(text) {
          return getBusinessTypeByValue(text)
        }
      },
      {
        title: '维护原因',
        dataIndex: 'reason',
        width: '10%',
      },
      {
        title: '维护时间',
        dataIndex: 'maintenanceTime',
        width: '10%',
      },
      {
        title: '预计修改时间',
        dataIndex: 'repairTime',
        width: '10%',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => <OptionNode record={record}></OptionNode>,
        width: '10%',
      },
    ];
  };

  render() {
    const { tableCol, ravDrawerConfig, onDrawerOk, changeDrawerStatus, handleSelectRows } = this;
    const { drawerStatus, resultDate, selectedRows, inputConfig } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    const drawerItem = drawerConfig[drawerStatus.type];
    const drawerTile = drawerItem ? drawerItem.title : '';
    const content = (
      <div>
        <Button style={{ float: 'right', marginLeft: '20px' }} onClick={() => this.changeDrawerStatus(true, 'add')} type="primary">
          新增
        </Button>
      </div>
    );
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <div style={{ marginBottom: '10px', height: '32px', lineHeight: '32px' }}>{content}</div>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              // showSelect
              selectedRows={selectedRows}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => index}
              // onSelectRow={this.handleSelectRows}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'cityconfigmsg/getCityMsgByPage');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title={drawerTile}
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false);
          }}
          onOk={e => {
            onDrawerOk();
          }}
          visible={drawerStatus.visible}
        >
          {drawerStatus.visible ? <div className={styles.drawerContent}>
            <BaseForm wrappedComponentRef={this.$drawerForm} formProp={formProp} inputConfig={ravDrawerConfig()}></BaseForm>
          </div> : ''}
        </Modal>
      </div>
    );
  }
}

export default CityConfigMsg;
